﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace MQC.export
{
    public partial class Search : System.Web.UI.Page
    {
        
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Export_Click(object sender, EventArgs e)
        {
            string maktx, mold;
            maktx = Maktx.Value.ToString().Trim().ToUpper();
            mold = Mold.Value.ToString().Trim().ToUpper();
            DateTime sDate = Convert.ToDateTime(SDate.Text.ToString().Trim());
            DateTime eDate = Convert.ToDateTime(EDate.Text.ToString().Trim());
            using(DbAppDataContext db = new DbAppDataContext())
            {
                var data = from m in db.Record
                           join n in db.Record_Cavity on m.Batch equals n.Batch
                           where m.Maktx == maktx && m.CreateDate >= sDate && m.CreateDate <= eDate && m.Mold == mold
                           select new DataType { Date = (DateTime)m.CreateDate, Content = n.Content, Result = n.Result,CavityNo=n.CavityNo,No=(double)n.No };
                var list = data.ToList();
                if(list.Count==0)
                {
                    string s = string.Format("<script>alert('没有找到数据');</script>");
                    Response.Write(s);
                }
                else
                {
                    GridView1.DataSource = list;
                    GridView1.DataBind();
                    ExportToExcel(GridView1);
                }
                
            }
        }

        public void ExportToExcel(GridView GridView)
        {
            string excelname = Maktx.Value.ToString().Trim().ToUpper() +" " + Mold.Value.ToString().Trim().ToUpper(); ;
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment;filename=  " + excelname + " .xls");
            Response.Charset = "gb2312";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); 
            Response.ContentType = "application/type.xls";//设置输出文件类型为excel文件      
            StringWriter stringWrite = new StringWriter();
            HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
            GridView.RenderControl(htmlWrite);
            Response.Write(stringWrite.ToString());
            Response.End();
        }

        public override void VerifyRenderingInServerForm(Control control)
        {
            // Confirms that an HtmlForm control is rendered for    
        }

    }
}